﻿using System;
using System.Collections.Generic;
using System.IO;

namespace Pvf.Core.Converters
{
    internal sealed class DynamicElementConverter<TEnum, TInterface, TFallbackImplType> : PvfBinaryConverter<TInterface>, IDynamicElementConverter
        where TEnum : struct
    {
        private IDictionary<int, DynamicElementEnumConverterData<TEnum>> _converters;

        public override TInterface Deserialize(BinaryReader reader, IPvfModule module = null)
        {
            return default;
        }

        protected override void OnInit()
        {
            _converters = PvfStatics.BuildDynamicConverter<TEnum>(Layout.Env, typeof(TInterface), typeof(TFallbackImplType));
            if (_converters != null)
            {
                Layout.Keys.AddRange(_converters.Keys);
            }
        }

        public IDynamicElementEnumConverterData GetSubConverterData(int key)
        {
            if (_converters == null)
            {
                return default;
            }
            _converters.TryGetValue(key, out var foundConverterData);
            return foundConverterData;
        }

        public Type GetBaseType()
        {
            return typeof(TInterface);
        }

        public Type GetEnumType()
        {
            return typeof(TEnum);
        }

        public void SetEntityKey(ref IDynamicElementEntity entity, IDynamicElementEnumConverterData converterData)
        {
            if(entity is IDynamicElementEntity<TEnum> enumEntity && converterData is DynamicElementEnumConverterData<TEnum> enumConverterData)
            {
                enumEntity.Key = enumConverterData.EnumValue;
            }
        }
    }
}
